<template>
  <div>
    <headerc :title="title"></headerc>
    <div class="c-main-make">
      <div style="padding: 40px;">
        <el-form :inline="true" :model="filterForm" class="demo-form-inline">
          <el-form-item>
            <el-input
              v-model="filterForm.vague"
              placeholder="姓名/账号/手机"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
              v-show="isInput"
              v-model="filterForm.postName"
              @click.native="changeInput"
              placeholder="选择职务"
            ></el-input>
            <el-select
              ref="positionInput"
              v-show="!isInput"
              v-model="filterForm.positionId"
              filterable
              remote
              reserve-keyword
              placeholder="选择职务"
              :remote-method="filterRemoteMethod"
              :loading="filterLoading"
              clearable
            >
              <el-option
                v-for="item in filterPositionOptions"
                :key="item.id"
                :label="item.postName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- </el-form-item> -->
          <el-form-item>
            <el-input
              v-model="filterForm.deptName"
              placeholder="选择部门"
              @click.native="goChangeDept(true)"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-select v-model="filterForm.status" placeholder="状态选项">
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="filterForm.loginDateTime"
              type="daterange"
              range-separator="至"
              start-placeholder="最后登录时间"
              end-placeholder="最后登录时间"
              value-format="yyyy-MM-dd"
              @change="changeDate"
              placeholder="最后登录"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="reset" v-auth="'B01001'"
              >清除查询条件</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="query"
              >查询</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button v-auth="'E03001'" type="primary" @click="createUser"
              >新增员工</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button v-auth="'E03002'" @click="exportExcel"
              >导出数据</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <el-table
        :data="userList"
        border
        :header-cell-style="{ background: '#F6F7FB' }"
      >
        <!-- <el-table-column type="selection" width="55"> </el-table-column> -->
        <el-table-column label="姓名">
          <template slot-scope="scope">
            <p>{{ scope.row.emplName }}</p>
          </template>
        </el-table-column>
        <el-table-column label="一级部门">
          <template slot-scope="scope">
            <!-- <p>{{ scope.row.deptDTO.name }}</p> -->
            <p>{{ scope.row.deptLevelName1 }}</p>
          </template>
        </el-table-column>
        <el-table-column label="二级部门">
          <template slot-scope="scope">
            <p>{{ scope.row.deptLevelName2 }}</p>
          </template>
        </el-table-column>
        <el-table-column label="职务">
          <template slot-scope="scope">
            <p>{{ scope.row.positionName }}</p>
          </template>
        </el-table-column>
        <el-table-column label="账号状态">
          <template slot-scope="{ row }">
            <p v-if="row.status == 1">启用</p>
            <p v-if="row.status == 2">禁用</p>
          </template>
        </el-table-column>
        <el-table-column label="手机" width="110">
          <template slot-scope="scope">
            <p>{{ scope.row.mobile }}</p>
          </template>
        </el-table-column>
        <el-table-column label="最后登录">
          <template slot-scope="scope">
            <p>{{ scope.row.loginDate | formatDate('yyyy-MM-dd') }}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="400">
          <template slot-scope="scope">
            <el-button
              v-auth="'E03005'"
              size="mini"
              @click="goDetail(scope.row.id)"
              >详情</el-button
            >
            <el-button v-auth="'E03002'" size="mini" @click="edit(scope.row)"
              >编辑</el-button
            >
            <el-button
              v-auth="'E03006'"
              size="mini"
              @click="goSetting(scope.row)"
              >设置</el-button
            >
            <el-button
              v-auth="'E03006'"
              size="mini"
              @click="goPassword(scope.row)"
              >修改密码</el-button
            >
            <el-button
              v-auth="'E03003'"
              size="mini"
              type="danger"
              @click="goDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="isUpdate"
        background
        layout="prev, pager, next"
        :page-size="pageSize"
        :total="total"
        :hide-on-single-page="total < 10"
        @current-change="currentChange"
        class="pagination"
      >
      </el-pagination>
    </div>

    <el-dialog
      title="设置"
      :visible.sync="settingDialogVisible"
      @close="cancelSettingDialog"
      width="50%"
    >
      <el-form
        ref="settingForm"
        :model="settingForm"
        :rules="settingRules"
        label-width="100px"
      >
        <el-form-item label="已选员工:" prop="emplName">
          <el-input
            v-model="settingForm.emplName"
            placeholder="输入内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="选择状态:" prop="status">
          <el-radio-group v-model="settingForm.status" size="medium">
            <el-radio border :label="1">启用</el-radio>
            <el-radio border :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择部门:" prop="dept">
          <el-input
            placeholder="选择部门"
            v-model="settingForm.dept"
            @click.native="goChangeDept(false)"
          ></el-input>
        </el-form-item>
        <el-form-item label="选择职务:" prop="positionId">
          <el-select
            v-model="settingForm.positionId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            :loading="loading"
            clearable
          >
            <el-option
              v-for="item in positionOptions"
              :key="item.id"
              :label="item.postName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注内容:">
          <el-input
            v-model="settingForm.remark"
            type="textarea"
            :rows="4"
            placeholder="输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelSettingDialog">取 消</el-button>
        <el-button type="primary" @click="setting">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="选择部门"
      :visible.sync="deptDialog"
      :close="cancelDeptDialog"
    >
      <el-form :inline="true" :model="filterForm" class="demo-form-inline">
        <el-form-item>
          <el-input
            v-model="filterDeptForm.deptName"
            placeholder="部门名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="query"
            >查询</el-button
          >
        </el-form-item>
      </el-form>

      <el-breadcrumb
        style="padding: 20px;"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          v-for="item in breadcrumbList"
          :key="item.id"
          @click.native="goBreadcrumb(item)"
          ><a>{{ item.name }}</a></el-breadcrumb-item
        >
      </el-breadcrumb>
      <el-table :data="deptList" border>
        <el-table-column label="部门名称">
          <template slot-scope="scope">
            <a href="javascript:void(0);" @click="nextDept(scope.row)">{{
              scope.row.name
            }}</a>
          </template>
        </el-table-column>
        <el-table-column label="部门级别">
          <template slot-scope="{ row }">
            <p v-if="row.deptLevel == 1">一级</p>
            <p v-if="row.deptLevel == 2">二级</p>
            <p v-if="row.deptLevel == 3">三级</p>
            <p v-if="row.deptLevel == 4">四级</p>
            <p v-if="row.deptLevel == 5">五级</p>
          </template>
        </el-table-column>
        <el-table-column label="选择">
          <template slot-scope="{ row }">
            <el-button
              v-if="deptType"
              type="text"
              @click="filterChangeDept(row)"
              >确认</el-button
            >
            <el-button v-if="!deptType" type="text" @click="changeDept(row)"
              >确认</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog
      width="35%"
      title="修改密码"
      :visible.sync="passwordDialog"
      @close="cancelChangePassword"
    >
      <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="100px">
        <el-form-item label="请输入密码" prop="password">
          <el-input
            style="width: 300px;"
            v-model="passwordForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelChangePassword">取 消</el-button>
        <el-button type="primary" @click="changePassword">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import headerc from '@/components/header.vue'
import { exportMethod } from '@/utils/utils'
import {
  positionList,
  deletePosition,
  updatePositionStatus,
  createPosition,
  updatePosition,
  updatePro,
  getParent,
  deptList,
  userList,
  updateUserPro,
} from '@/api/permission'
import { getUser } from '@/api'

export default {
  components: {
    headerc,
  },
  data() {
    return {
      passwordDialog: false,
      isInput: false,
      filterPositionOptions: [],
      isUpdate: true,
      title: '员工管理',
      dialogVisible: false,
      dialogVisible2: false,
      settingDialogVisible: false,
      dialogVisible4: false,
      positionDialog: false,
      deptDialog: false,
      positionOptions: [],
      breadcrumbList: [{ name: '新疆中泰矿冶有限公司', id: '0' }],
      props: {
        // props定义的值根据接口返回的数据定的
        label: 'name',
        value: 'id',
        children: 'data',
      },
      passwordForm: {
        password: '',
      },
      loading: false,
      filterLoading: false,
      statusList: [
        {
          value: 0,
          label: '全部',
        },
        {
          value: 1,
          label: '启用',
        },
        {
          value: 2,
          label: '禁用',
        },
      ],
      addJob: {
        jobName: '',
        description: '',
        remark: '',
      },
      deptForm: {
        users: '',
        dept: '',
        remark: '',
      },
      positionForm: {
        position: '',
        remark: '',
      },
      setStates: {
        chooseState: [],
        remakes: '',
      },
      settingForm: {
        emplName: '',
        status: 1,
        remake: '',
      },
      pageNo: 1, // 分页页码
      pageSize: 10, // 每页条数
      total: 0,
      userList: [],
      settingRow: '',
      positionRow: '',
      passwordRow: '',
      filterForm: {
        vague: '',
        positionId: '',
        postName: '',
        deptId: '',
        deptName: '',
        status: 0,
        loginDateTime: '',
      },
      filterDeptForm: {
        deptName: '',
      },
      passwordForm: {
        password: '',
      },
      deptRules: {
        dept: [{ required: true, message: '请选择部门', trigger: 'change' }],
      },
      positionRules: {
        position: [{ required: true, message: '请选择职务', trigger: 'blur' }],
      },
      settingRules: {
        emplName: [{ required: true, message: '请添加员工', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
      },
      passwordRules: {
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      },
      deptOptions: [],
      multipleSelection: [],
      parentId: '0',
      deptList: [],
      staff: [],
      deptId: '',
      positionId: '',
      userInfo: {},
      deptType: true,
    }
  },
  created() {
    const buttons = this.$store.getters.buttons
    this.filterForm.deptId = this.$route.query.deptId
    this.filterForm.deptName = this.$route.query.deptName
    this.isInput = true
    this.filterForm.positionId = this.$route.query.positionId
    this.filterForm.postName = this.$route.query.postName
    this.getUserList()
  },
  methods: {
    cancelChangePassword() {
      this.passwordDialog = false
      this.$refs.passwordForm.resetFields()
    },
    goPassword(row) {
      this.passwordDialog = true
      this.passwordRow = row
    },
    async changePassword() {
      this.$refs.passwordForm.validate(async (valid) => {
        if (valid) {
          const res = await updateUserPro([{
            id: this.passwordRow.id,
            password: this.passwordForm.password,
          }])
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '密码设置成功',
            })
            this.passwordDialog = false
            this.getUserList()
          }
        } else {
          return false
        }
      })
    },
    changeInput() {
      this.isInput = false
      this.filterForm.positionId = ''
      this.filterForm.postName = ''
      this.$refs.positionInput.focus()
      // console.log("this.$refs.positionInput",this.$refs.positionInput)
    },
    exportExcel() {
      const data = {
        deptId: this.filterForm.deptId2,
        loginDateEnd: this.filterForm.loginDateTime[1],
        loginDateStart: this.filterForm.loginDateTime[0],
        pageNo: this.pageNo,
        pageSize: 5000,
        positionId: this.filterForm.positionId,
        vague: this.filterForm.vague,
        status: 0,
      }

      exportMethod('user1', data, '员工信息')
    },
    async goDelete(row) {
      const res = await updateUserPro([
        {
          id: row.id,
          isDeleted: 2,
        },
      ])
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: '删除成功',
        })

        this.getUserList()
      }
    },
    async edit(row) {
      const res = await getUser(row.id)
      if (res.code == 200) {
        this.userInfo = res.data
        this.$router.push({
          path: '/archives/createUser',
          query: {
            userInfo: encodeURIComponent(JSON.stringify(this.userInfo)),
            type:2
          },
        })
      }
    },
    setting() {
      this.$refs.settingForm.validate(async (valid) => {
        if (valid) {
          const res = await updateUserPro([
            {
              id: this.settingRow.id,
              status: this.settingForm.status,
              deptId: this.deptId,
              positionId: this.settingForm.positionId,
            },
          ])
          if (res.code == 200) {
            this.settingDialogVisible = false
            this.$message({
              type: 'success',
              message: '设置成功',
            })
            this.getUserList()
          }
        } else {
          return false
        }
      })
    },
    goSetting(row) {
      this.settingDialogVisible = true
      this.settingRow = row
      this.settingForm.emplName = row.emplName
    },
    async filterRemoteMethod(query) {
      if (query !== '') {
        this.filterLoading = true
        const res = await positionList({
          pageNo: 1,
          pageSize: 5000,
          postName: query,
        })
        if (res.code == 200) {
          console.log(res, 'res')
          this.filterLoading = false
          this.filterPositionOptions = res.data.list
        }
      } else {
        this.filterPositionOptions = []
      }
    },
    changePosition(val) {
      this.positionId = val
    },
    filterChangeDept(row) {
      this.filterForm.deptId = row.id
      this.filterForm.deptName = row.name
      this.deptDialog = false
    },
    changeDept(row) {
      this.deptId = row.id
      this.settingForm.dept = row.name
      this.deptDialog = false
    },
    nextDept(row) {
      if (
        this.breadcrumbList[row.deptLevel] &&
        row.id != this.breadcrumbList[row.deptLevel].id
      ) {
        this.breadcrumbList.splice(row.deptLevel, 1, {
          name: row.name,
          id: row.id,
          deptLevel: row.deptLevel,
          parentIdList: row.parentIdList,
        })
        this.breadcrumbList.splice(row.deptLevel + 1)
      } else {
        if (this.breadcrumbList.length < 5) {
          this.breadcrumbList.push({
            name: row.name,
            id: row.id,
            deptLevel: row.deptLevel,
            parentIdList: row.parentIdList,
          })
          this.parentId = row.id
          this.getDeptList()
        }
      }
      // if (row.deptLevel < 5) {
      //   this.parentId = row.id
      //   this.getDeptList()
      // }
    },
    cancelDeptDialog() {
      this.deptDialog = false
      this.$refs.positionForm.resetFields()
    },
    // async getDeptList() {
    //   const res = await getParent(this.parentId)
    //   // console.log('res', res)
    //   if (res.code == 200) {
    //     this.deptList = res.data
    //     this.deptLevel = res.data[0].deptLevel
    //     // console.log('this.deptLevel',res.data[0].deptLevel)
    //     // this.total = res.data.total
    //   }
    // },
    async getDeptList() {
      const res = await deptList({
        deptLevel: this.deptLevel,
        deptName: this.filterDeptForm.deptName,
        isPage: false,
        pageNo: 1,
        pageSize: 5000,
        parentDeptId: this.parentId,
      })

      if (res.code == 200) {
        this.deptList = res.data.list
        this.deptLevel = res.data.list[0].deptLevel
        // console.log('this.deptLevel',res.data[0].deptLevel)
        // this.total = res.data.total
      }
    },
    goBreadcrumb(item) {
      this.parentId = item.id
      this.getDeptList()
      if (item.deptLevel) {
        this.breadcrumbList.splice(item.deptLevel + 1)
      } else {
        this.breadcrumbList.splice(1)
      }
    },
    // async deptFocus() {
    //   const res = await getParent(0)
    //   if (res.code == 200) {
    //     this.deptOptions = res.data
    //     this.deptOptions.forEach((item, index) => {
    //       //添加属性
    //       this.$set(this.deptOptions[index], 'data', [])
    //     })
    //   }
    // },
    // async expandChangeDept(val) {
    //   let value = val[0]
    //   console.log('val', val)
    //   const res = await getParent(value)
    //   if (res.code == 200) {
    //     const arr = res.data || []
    //     for (let i = 0; i < this.deptOptions.length; i++) {
    //       if (this.deptOptions[i].id === value) {
    //         this.$set(this.deptOptions[i], 'data', arr)
    //         break
    //       }
    //     }
    //   }
    // },
    goChangeDept(val) {
      this.deptType = val
      this.deptDialog = true
      this.getDeptList()
    },
    // async updatePosition() {
    //   const data = this.staff.map((item) => {
    //     return {
    //       positionId: this.positionId,
    //       emplName: item.emplName,
    //       id: item.id,
    //     }
    //   })

    //   const res = await updateUser(data)
    //   if (res.code == 200) {
    //     this.$message({
    //       type: 'success',
    //       message: '职务修改成功',
    //     })
    //     this.positionDialog = false
    //     this.staff = []
    //     this.getUserList()
    //   }
    // },
    async remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        const res = await positionList({
          pageNo: 1,
          pageSize: 5000,
          postName: query,
        })
        if (res.code == 200) {
          this.loading = false
          this.positionOptions = res.data.list
        }
      } else {
        this.positionOptions = []
      }
    },
    goUpdatePosition() {
      if (!this.multipleSelection.length) {
        this.$message({
          type: 'error',
          message: '请选择员工',
        })
        return
      }
      this.positionDialog = true
      this.staff = this.multipleSelection.map((item) => item)
    },
    goUpdateDept() {
      if (!this.multipleSelection.length) {
        this.$message({
          type: 'error',
          message: '请选择员工',
        })
        return
      }
      this.dialogVisible2 = true
      this.staff = this.multipleSelection.map((item) => item)
    },
    async updateDept() {
      const data = this.staff.map((item) => {
        return {
          deptId: this.deptId,
          emplName: item.emplName,
          id: item.id,
        }
      })

      const res = await updateUserPro(data)
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: '部门修改成功',
        })
        this.dialogVisible2 = false
        this.staff = []
        this.getUserList()
      }
    },
    createUser() {
      this.$router.push({
        path: '/archives/createUser',
        query:{
          type:1
        }
      })
    },
    changeDate(date) {
      this.filterForm.loginDateTime = date
    },
    goDetail(id) {
      this.$router.push({
        path: '/archives/userDetail',
        query: {
          id,
        },
      })
    },
    reset() {
      this.filterForm.vague = ''
      this.filterForm.positionId = ''
      this.filterForm.deptId = ''
      this.filterForm.status = 0
      this.filterForm.loginDateTime = ''
    },
    query() {
      this.pageNo = 1
      this.isUpdate = false
      this.getUserList()
    },
    currentChange(pageNo) {
      this.pageNo = pageNo
      this.getUserList()
    },
    async getUserList() {
      const res = await userList({
        loginDateEnd: this.filterForm.loginDateTime[1],
        loginDateStart: this.filterForm.loginDateTime[0],
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        positionId: this.filterForm.positionId,
        deptId: this.filterForm.deptId,
        status: this.filterForm.status,
        vague: this.filterForm.vague,
      })
      if (res.code == 200) {
        this.isUpdate = true
        this.userList = res.data.list
        console.log('this.userList', this.userList)
        this.total = res.data.total
      }
    },
    // cancelPosition() {
    //   this.positionDialog = false
    //   this.$refs.positionForm.resetFields()
    // },
    cancel2() {
      this.dialogVisible2 = false
      this.$refs.deptForm.resetFields()
    },
    cancelSettingDialog() {
      this.settingDialogVisible = false
      this.$refs.settingForm.resetFields()
    },
    setAuthority() {
      this.$router.push('jobset')
    },
    handleEdit(index, row) {
      console.log(index, row)
    },
    handleDelete(index, row) {
      console.log(index, row)
    },
    deleteSure() {
      this.dialogVisible4 = false
      this.$message({
        message: '恭喜你，这是一条成功消息',
        type: 'success',
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.c-main-make {
  margin-left: 35px;
  min-height: 300px;
  background: #fff;
  margin-right: 35px;
  margin-bottom: 35px;
  //   position: relative;
  //   overflow: hidden;
  border: 1px #dcdee0 solid;
}
.c-main-show {
  margin-left: 35px;
  min-height: 700px;
  background: #fff;
  margin-right: 35px;
  margin-bottom: 35px;
  //   position: relative;
  //   overflow: hidden;
  border: 1px #dcdee0 solid;
}
.title-text {
  width: 100%;
  height: 50px;
  border-bottom: 1px #dcdee0 solid;
  font-family: '微软雅黑 Bold', '微软雅黑 Regular', 微软雅黑, sans-serif;
  font-weight: 700;
  color: #666666;
  line-height: 50px;
  padding-left: 25px;
}
.emplnames {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  padding: 0 15px;
  background-color: #f5f7fa;
}

.pagination {
  display: flex;
  justify-content: end;
}
</style>
